package com.demo.rocketmq.constants;

import lombok.extern.slf4j.Slf4j;

/**
 * RocketMQ 延时级别
 * 级别分别是1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
 * @author cyj
 */
@Slf4j
public enum DelayLevelEnum {
    /**
     * 1s
     */
    LEVEL_1(1,1),
    /**
     * 5s
     */
    LEVEL_2(2,5),
    /**
     * 10s
     */
    LEVEL_3(3,10),
    /**
     * 30s
     */
    LEVEL_4(4,30),
    /**
     * 1m
     */
    LEVEL_5(5,60),
    /**
     * 2m
     */
    LEVEL_6(6,120),
    /**
     * 3m
     */
    LEVEL_7(7,180),
    /**
     * 4m
     */
    LEVEL_8(8,240),
    /**
     * 5m
     */
    LEVEL_9(9,300),
    /**
     * 6m
     */
    LEVEL_10(10,360),
    /**
     * 7m
     */
    LEVEL_11(11,420),
    /**
     * 8m
     */
    LEVEL_12(12,480),
    /**
     * 9m
     */
    LEVEL_13(13,540),
    /**
     * 10m
     */
    LEVEL_14(14,600),
    /**
     * 20m
     */
    LEVEL_15(15,1200),
    /**
     * 30m
     */
    LEVEL_16(16,1800),
    /**
     * 1h
     */
    LEVEL_17(17,3600),
    /**
     * 2h
     */
    LEVEL_18(18,7200);

    private final Integer level;
    private final Integer time;

    DelayLevelEnum(int level, int time) {
        this.level = level;
        this.time = time;
    }

    public Integer getLevel() {
        return level;
    }

    public Integer getTime() {
        return time;
    }

    /**
     * 计算时间对应延时级别
     * @param second 秒
     * @return 延时级别枚举对象
     */
    public static DelayLevelEnum calculateDefault(long second) {
        int level = 0;
        // 通过循环计算找出延时等级，算出第一个延时等级终止循环
        for (int i = DelayLevelEnum.values().length - 1; i >= 0 ; i--) {
            Integer delayTime = DelayLevelEnum.values()[i].time;
            long l = second / delayTime;
            log.debug("时间：{}", l);
            if (l > 0) {
                level = i;
                break;
            }
        }

        if (level > DelayLevelEnum.LEVEL_18.level) {
            level = DelayLevelEnum.LEVEL_18.level;
        }
        return DelayLevelEnum.values()[level];
    }

    public static Integer getTime(int level) {
        for (DelayLevelEnum value : DelayLevelEnum.values()) {
            if (value.level == level) {
                return value.time;
            }
        }
        return 0;
    }
}
